import * as odocRequestAPI from '../apis/odocRequest/odocRequest';
import { Modal, message } from 'antd';
import { WeaLocaleProvider } from 'ecCom';
import jQuery from 'jquery';
import queryString from '../util/getUrlParamsUtil';

const getLabel = WeaLocaleProvider.getLabel;

export default class OdocEvent4Export {
  workflowStores = {};

  constructor() {
    this.setWorkflowStores = this.setWorkflowStores.bind(this);
    this.resetWorkflowStores = this.resetWorkflowStores.bind(this);
    this.getLastOperateInfo = this.getLastOperateInfo.bind(this);
  }

  setWorkflowStores(stores = {}) {
    this.workflowStores = stores;
  }

  resetWorkflowStores() {
    this.workflowStores = {};
  }


  goSignApprovalEvent(url) {
    let context_height = jQuery('.wea-new-top-req-content').height();
    jQuery('.wf-append-iframe').css({ display: 'block', height: context_height });
    jQuery('.custom-tab-iframe').css({ display: 'none' });
    if (jQuery('.custom-haoqian-iframe').length <= 0) {
      jQuery('.wf-append-iframe').append(`<iframe class="custom-haoqian-iframe" src="${url}" style="width:100%;height:100%;border:none"></iframe>`);
    } else {
      jQuery('.custom-haoqian-iframe').css({ display: 'block' });
    }
  }

  sendConfirmTip(title, content, callback) {
    if (title == '') {
      title = getLabel('28535', '信息提示');
    }
    Modal.warning({
      title,
      content,
      onOk() {
        callback && typeof callback == 'function' && callback();
      },
      okText: getLabel('826', '确定'),
    });
  }

  doCheckSignApprovalFile = (requestid, type, userid) => {
    let commonParam = WfForm.getGlobalStore().commonParam;
    const { f_weaver_belongto_userid, f_weaver_belongto_usertype } = commonParam;
    odocRequestAPI.checkSeal({ requestid, checktype: type, userid, f_weaver_belongto_userid, f_weaver_belongto_usertype }).then(() => { });
  }
  /**
   * 签批页签事件绑定
   */
  bindSignApprovalTabEvent() {
    let _that = this;
    let timer = setInterval(() => {
      let commonParam = WfForm.getGlobalStore().commonParam;
      if (commonParam.requestid && commonParam.requestid > 0) {
        clearInterval(timer);
        const { workflowid, nodeid, requestid, f_weaver_belongto_userid, f_weaver_belongto_usertype } = commonParam;
        let params = { workflowid, requestid, nodeid, islock: 1, f_weaver_belongto_userid, f_weaver_belongto_usertype };

        let url = `/spa/odoc/static/index.html#/main/offical/odocSignApproval?workflowid=${workflowid}&requestid=${requestid}&nodeid=${nodeid}`;
        odocRequestAPI.isSeal(params).then((data) => {
          if (data.api_status && data.api_status == 1) {
            if (data.isView == true) {
              WfForm.registerAction(WfForm.ACTION_SWITCHTAB, (toTab, fromTab) => {
                if (toTab == 'custom_iframe_haoqian') {
                  _that.goSignApprovalEvent(url);
                } else if (fromTab == 'custom_iframe_haoqian') {
                  jQuery('.custom-haoqian-iframe').css({ display: 'none' });
                  jQuery('.custom-tab-iframe').css({ display: 'block' });
                }
              });
              if (data.isOpen && data.isOpen == true) {
                WfForm.getGlobalStore().setTabKey('custom_iframe_haoqian');
                _that.goSignApprovalEvent(url);
              }

              if (data.isSeal && data.isSeal == true) {
                window.openSignApproval = true;
                // 文档签入
                window.onbeforeunload = function () {
                  _that.doCheckSignApprovalFile(requestid, 2, data.userid);
                };
                let intervalTime = parseInt(data.recheckoutminute) * 60000 || 600000;
                setInterval(() => {
                  // 文档签出
                  _that.doCheckSignApprovalFile(requestid, 1, data.userid);
                }, intervalTime);
              }
            }
          } else {
            message.error(data.msg || '获取数据异常');
          }

          // 必签
          if (data.isMust && data.isMust == true) {
            WfForm.registerCheckEvent(WfForm.OPER_SUBMIT, (callback) => {
              odocRequestAPI.hasSeal(params).then((data1) => {
                if (data1.api_status && data1.api_status == 1) {
                  if (data1.hasSeal && data1.hasSeal == true) {
                    callback();
                  } else {
                    let haoqianIframe = jQuery('.custom-haoqian-iframe');
                    if (haoqianIframe.length > 0) {
                      let haoqianIframeCtx = haoqianIframe[0].contentWindow.signApprovalCtx;
                      if (haoqianIframeCtx) {
                        haoqianIframeCtx.CloseWrite();
                        if (haoqianIframeCtx.CheckoutHasUnsaveData()) {
                          haoqianIframeCtx.SimulateClickBtn('wsSaveBtn');
                          setTimeout(() => {
                            callback();
                          }, 1000);
                        } else {
                          _that.sendConfirmTip('', data1.msg || '签批未完成,无法提交此流程', () => {
                            WfForm.switchTab('custom_iframe_haoqian');
                            if ((data1.sealTerminal && data1.sealTerminal < 1) || data.defaultSign == true) {
                              if (haoqianIframe[0].contentWindow.odocSignApprovalStore) {
                                let odocSignApprovalStore = haoqianIframe[0].contentWindow.odocSignApprovalStore
                                if (odocSignApprovalStore.qpSelected == true || data.defaultSign == true) {
                                  odocSignApprovalStore.setQpSelected(true);
                                  haoqianIframeCtx.SimulateClickBtn('writeBtn');
                                }
                              }
                            }
                          });
                        }
                      }
                    } else {
                      _that.sendConfirmTip('', data1.msg || '签批未完成,无法提交此流程', () => {
                        WfForm.switchTab('custom_iframe_haoqian');
                      });
                    }
                  }
                } else {
                  message.error(data1.msg || '获取数据异常');
                }
              });
            });
          }
        });
      }
    }, 500);
  }


  /**
   * PC端自定义tab页签事件绑定
   */
  bindCustomTabEvent() {
    let _that = this;
    let urlParams = queryString();
    let { workflowid = '', requestid = '', _workflowid = '' } = urlParams;
    workflowid = workflowid == '' ? (_workflowid == '' ? '' : _workflowid) : workflowid;
    let params = {
      workflowid,
      requestid,
    };
    odocRequestAPI.getOdocTabManagerDatas(params).then((data) => {
      if (data.api_status && data.api_status == true) {
        let customTabs = data.customTabs;
        customTabs.map((item) => {
          let { key, url } = item;
          if (key.indexOf('custom_iframe_workflowCusTab_') >= 0) {
            window.WfForm.bindCustomTabEvnent(key, () => {
              _that.fnTabClick(key, url);
            });
          }
        });
      }
    });
  }

  fnTabClick = (key, url) => {
    let context_height = jQuery('.wea-new-top-req-content').height();
    jQuery('.wf-append-iframe').css({ display: 'block', height: context_height });
    let lastSrc = jQuery('.custom-tab-iframe').attr('src');
    jQuery('.custom-tab-iframe').attr('src', url);
    let newSrc = url.split('?')[0];
    if (lastSrc.indexOf(newSrc) >= 0) {
      jQuery('.custom-tab-iframe')[0].contentWindow.location.reload();
    }
  };

  /**
   * 确定结束本人处理回调
   */
  doEndMyRequestConfirm = (data, operate) => {
    const { commonParam = {}, submitParam = {}, baseParam = {} } = this.workflowStores;
    const { workflowid, nodeid } = commonParam;
    const { requestid } = submitParam;
    const isDrawEnd = data.isEndPerson ? 1 : 0;
    const { f_weaver_belongto_userid, f_weaver_belongto_usertype } = baseParam;

    let remark = '';
    try {
      remark = window.CK_REF.remark.getEditor().getData();
    } catch (e) {
    }

    let params = {
      isend: 1,
      workflowid,
      nodeid,
      requestid,
      remark,
      isDrawEnd,
      f_weaver_belongto_userid,
      f_weaver_belongto_usertype,
    };

    odocRequestAPI.doEndPersonTreat(params).then((datas) => {
      if (datas.api_status && datas.api_status == true) {
        operate.onSuccess();
      } else {
        message.error(getLabel(30651, '操作失败'));
        operate.onClose();
      }
    });
  }

  /**
   * 结束本人处理
   * @param operate
   */
  doEndMyRequest = (operate) => {
    let _that = this;
    const { submitParam = {}, baseParam = {} } = this.workflowStores;
    const { requestid } = submitParam;
    const { f_weaver_belongto_userid, f_weaver_belongto_usertype } = baseParam;
    odocRequestAPI.isEndTreatPerson({ requestid, f_weaver_belongto_userid, f_weaver_belongto_usertype }).then((data) => {
      if (data.api_status && data.api_status == true) {
        let msg = '';
        if (data.isEndPerson == true) {
          msg = getLabel(519952, '您是此公文的唯一办理人员，确定要把文件送归档员存档吗？');
        } else {
          msg = getLabel(519953, '您确认结束本人处理吗？');
        }
        Modal.confirm({
          title: getLabel(131329, '信息确认'),
          content: msg,
          okText: getLabel(826, '确定'),
          cancelText: getLabel(201, '取消'),
          onOk() {
            _that.doEndMyRequestConfirm(data, operate);
          },
          onCancel() {
            operate.onClose();
          },
        });
      }
    });
  }


  /**
   * 流程跟踪 1: 跟踪，0：取消跟踪
   * @param flag
   */
  doFollowRequest = (flag, reloadMenu) => {
    const { submitParam = {}, commonParam = {} } = this.workflowStores;
    const { requestid } = submitParam;
    const { f_weaver_belongto_userid, f_weaver_belongto_usertype } = commonParam;
    if (requestid && requestid > 0) {
      if (flag == 1) {
        odocRequestAPI.doFollowRequest({ requestid, f_weaver_belongto_userid, f_weaver_belongto_usertype }).then((data) => {
          if (data.api_status && data.api_status == true) {
            message.success(`${getLabel(131972, '流程跟踪')}${getLabel(15242, '成功')}`);
            reloadMenu();
          } else {
            message.error(`${getLabel(131972, '流程跟踪')}${getLabel(498, '失败')}`);
          }
        });
      } else {
        odocRequestAPI.removeFollowRequest({ requestid, f_weaver_belongto_userid, f_weaver_belongto_usertype }).then((data) => {
          if (data.api_status && data.api_status == true) {
            message.success(`${getLabel(201, '取消')}${getLabel(131972, '流程跟踪')}${getLabel(15242, '成功')}`);
            reloadMenu();
          } else {
            message.error(`${getLabel(201, '取消')}${getLabel(131972, '流程跟踪')}${getLabel(498, '失败')}`);
          }
        });
      }
    }
  }


  /**
   * 获取流程上一次操作的信息
   * @param requestid
   * @param callback
   */
  getLastOperateInfo(requestid, callback) {
    odocRequestAPI.getLastOperateInfo({ requestid }).then(
      (data) => {
        callback && typeof callback == 'function' && callback(data);
      },
    );
  }

  /**
   * 强制归档
   */
  doForceArchive(callback) {
    const confirmEvent = () => {
      const { commonParam = {}, submitParam = {} } = this.workflowStores;
      const { workflowid, nodeid, f_weaver_belongto_userid, f_weaver_belongto_usertype } = commonParam;
      const { requestid } = submitParam;

      let remark = '';
      try {
        remark = window.CK_REF.remark.getEditor().getData();
      } catch (e) {
      }

      let params = {
        workflowid,
        nodeid,
        requestid,
        f_weaver_belongto_userid,
        f_weaver_belongto_usertype,
        remark,
      };

      odocRequestAPI.forceArchive(params).then((data) => {
        const { success } = data;

        if (success) {
          callback && typeof callback == 'function' && callback();
        } else {
          const { msg = getLabel(30651, '操作失败') } = data;
          message.error(msg);
        }
      });
    };

    Modal.confirm({
      title: getLabel(131329, '信息确认'),
      content: getLabel(131982, '是否强制归档此流程'),
      okText: getLabel(826, '确定'),
      cancelText: getLabel(201, '取消'),
      onOk: confirmEvent.bind(this),
      onCancel: () => {
      },
    });
  }
}
